package com.kelvin.paopao.module.login.register.updateAvatar;

import android.content.Intent;
import android.os.Environment;

import com.hyphenate.EMCallBack;
import com.kelvin.kelvinlib.bitmap.BitmapUtil;
import com.kelvin.kelvinlib.utils.LogUtil;
import com.kelvin.kelvinlib.utils.ToastUtil;
import com.kelvin.paopao.api.RetrofitService;
import com.kelvin.paopao.api.ThrowableConsumer;
import com.kelvin.paopao.api.responseBean.CommonListResponse;
import com.kelvin.paopao.api.responseBean.UserDetailModel;
import com.kelvin.paopao.easemob.EaseMobHelper;
import com.kelvin.paopao.module.main.MainActivity;
import com.kelvin.paopao.utils.Constant;
import com.kelvin.paopao.utils.DialogMaker;
import com.hyphenate.easeui.utils.SpUtil;

import java.io.File;
import java.io.FileOutputStream;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;


/**
 * Created by MCK on 2017/5/8.
 */

public class UpdateAvatarPresenter implements IUpdateAvatarPresenter {

    private UpdateAvatarActivity mView;

    public UpdateAvatarPresenter(UpdateAvatarActivity view) {
        this.mView = view;
    }

    @Override
    public void compressAndUpdate(final String filepath, final String user_sex, final String user_id,
                                  final String user_name,
                                  final String user_pwd, final String user_tel, final String province,
                                  final String city, final String user_age, final String code, final String wechat_id
    ) {
        Luban.get(mView)
                .load(new File(filepath))                     //传人要压缩的图片
                .putGear(Luban.THIRD_GEAR)      //设定压缩档次，默认三挡
                .setCompressListener(new OnCompressListener() { //设置回调

                    @Override
                    public void onStart() {
                        DialogMaker.showProgressDialog(mView, "注册中，请稍候~~");
                    }

                    @Override
                    public void onSuccess(final File file) {
                        LogUtil.d("file:" + file.getAbsolutePath());
                        Observable.create(new ObservableOnSubscribe<File>() {
                            @Override
                            public void subscribe(@NonNull ObservableEmitter<File> e) throws Exception {
                                e.onNext(file);
                            }
                        }).flatMap(new Function<File, ObservableSource<CommonListResponse>>() {
                            @Override
                            public ObservableSource<CommonListResponse> apply(@NonNull File file) throws Exception {
                                String base64 = BitmapUtil.fileToBase64(file);
                                base64.replace("+", "%2B");
                                return RetrofitService.register(user_sex, user_id, user_name, user_pwd,
                                        user_tel, base64, province, city, user_age, code);
                            }
                        }).flatMap(new Function<CommonListResponse, ObservableSource<CommonListResponse<UserDetailModel>>>() {
                            @Override
                            public ObservableSource<CommonListResponse<UserDetailModel>> apply(@NonNull CommonListResponse commonListResponse) throws Exception {
                                if (!commonListResponse.getReason().equals("成功")) {
                                    ToastUtil.showToastOnThread(mView, commonListResponse.getReason());
                                    return null;
                                }
                                return RetrofitService.login(user_id, user_pwd, wechat_id);
                            }
                        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<CommonListResponse<UserDetailModel>>() {
                            @Override
                            public void accept(@NonNull CommonListResponse<UserDetailModel> userDetailModelCommonListResponse) throws Exception {
                                if (userDetailModelCommonListResponse.getReason().equals("成功")) {
                                    String user_no = userDetailModelCommonListResponse.getResult().get(0).getUser_no();
                                    SpUtil.setLoginHuanxin_id(mView, user_no);

                                    String user_nickname = userDetailModelCommonListResponse.getResult().get(0).getUser_name();
                                    String user_headimg = userDetailModelCommonListResponse.getResult().get(0).getUser_headimg();

                                    SpUtil.setLoginUserName(mView, user_nickname);
                                    SpUtil.setLoginAvatar(mView, user_headimg);

                                    String user_id = userDetailModelCommonListResponse.getResult().get(0).getUser_tel();
                                    SpUtil.setLoginphone(mView, user_id);

                                    EaseMobHelper.getInstance().login(user_no, new EMCallBack() {
                                        @Override
                                        public void onSuccess() {
                                            Intent intent = new Intent(mView, MainActivity.class);
                                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                            mView.startActivity(intent);
                                            DialogMaker.diamiss();
                                            Constant.IS_LOGIN = true;
                                        }

                                        @Override
                                        public void onError(int i, String s) {
                                            ToastUtil.showToast(mView, "登录失败");
                                            DialogMaker.diamiss();
                                        }

                                        @Override
                                        public void onProgress(int i, String s) {

                                        }
                                    });
                                } else {
                                    ToastUtil.showToast(mView, userDetailModelCommonListResponse.getReason());
                                    DialogMaker.diamiss();
                                }
                            }
                        }, new ThrowableConsumer(mView), new Action() {
                            @Override
                            public void run() throws Exception {
                                DialogMaker.diamiss();
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {
                        DialogMaker.diamiss();
                    }
                }).launch();    //启动压缩
    }

    @Override
    public void getData(boolean isRefresh) {

    }

    @Override
    public void getMoreData() {

    }
}
